<?php
/**
 * Created by PhpStorm
 * User: Jhinwy
 * Date: 6/18/24
 * Time: 2:15 PM
 */

namespace App\Services;

use App\Models\WechatAccountCheckinRecord;
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
use Illuminate\Support\Facades\Log;

class CheckinRecordService
{
    public static $axisPool = [
        [34.790742, 113.541593],
        [34.790478, 113.54161],
        [34.791448, 113.541461],
        [34.790145, 113.541555],
        [34.78979, 113.541478],
        [34.791659, 113.541105],
        [34.790131, 113.542749],
        [34.790858, 113.542432],
    ];

    public static $isNotDep = [1];

    public static $isNotUser = ['管理员'];

    public static $locationTitle = '河南省国家大学科技园';

    public static $locationDetail = '河南省国家大学科技园西区Y23栋';


    /**
     * 员工打卡记录
     *
     * @param $accessToken
     * @param $type
     * @param $userId
     * @return bool
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function checkinRecord($accessToken, $type, $corpId, $depId, $userId, $userName)
    {
        // // 排除不需要打卡的用户
        // if (in_array($depId, self::$isNotDep) || in_array($userName, self::$isNotUser)) {
        //
        //     return false;
        // }

        try {
            $axis = self::getCheckinAxis();
            $time = self::getCheckinTime($type);

            $record = [
                'userid'          => $userId,
                'checkin_time'    => $time,
                'location_title'  => self::$locationTitle,
                'location_detail' => self::$locationDetail,
                'notes'           => self::getNotes($type),
                'lat'             => (int)($axis[0] * 1000000),
                'lng'             => (int)($axis[1] * 1000000),
                'device_type'     => 3,
                'device_detail'   => '小米手机'
            ];

            $body     = [
                'headers'            => ['Content-Type' => 'application/json'],
                RequestOptions::JSON => [
                    'records' => [$record]
                ]
            ];
            $client   = new Client();
            $response = $client->request('POST', sprintf(config('corp_wechat.checkin_record'), $accessToken), $body);
            if ($response->getStatusCode() != 200) {
                throw new \Exception('请求失败！');
            }
            $contents = $response->getBody()->getContents();
            Log::info('员工打卡记录：', [$contents]);
            $data = json_decode($contents, true);
            if ($data['errcode'] != 0) {

                return false;
            }
            $date                         = date('Y-m-d');
            $recordModel                  = WechatAccountCheckinRecord::query()->firstOrNew(['user_id' => $userId, 'checkin_date' => $date]);
            $recordModel->corp_id         = $corpId;
            $recordModel->location_detail = self::$locationDetail;
            if ($type == 1) {
                $recordModel->top_checkin_time = date('Y-m-d H:i:s', $time);
            } else {
                $recordModel->down_checkin_time = date('Y-m-d H:i:s', $time);
            }
            $recordModel->device_type   = 3;
            $recordModel->device_detail = '小米手机';
            $recordModel->save();

            return true;
        } catch (\Exception $exception) {
            Log::error('添加员工打卡记录失败：' . $exception->getMessage());

            return false;
        }
    }


    /**
     * 获取打卡时间
     *
     * @param $type
     * @return int
     */
    public static function getCheckinTime($type)
    {
        if ($type == 1) {
            $start = strtotime(date('Y-m-d 08:00:00'));
            $end   = strtotime(date('Y-m-d 08:59:59'));

            return mt_rand($start, $end);
        } else {
            $start = strtotime(date('Y-m-d 18:01:00'));
            $end   = strtotime(date('Y-m-d 19:00:00'));

            return mt_rand($start, $end);
        }
    }


    public static function getNotes($type)
    {
        return $type == 1 ? '上班打卡' : '下班打卡';
    }


    public static function getCheckinAxis(): array
    {
        return self::$axisPool[array_rand(self::$axisPool)];
    }
}
